package edu.ajou.scw;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

/**
 * Servlet implementation class UserImage
 */
@WebServlet("/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Register() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		ServletContext context = getServletContext();
		
		String saveFolder = "/profile";
		
		//String savePath = context.getRealPath(saveFolder) + "/";
		String savePath = "/home/tomcat7" + saveFolder;
		
		File f = new File(savePath);
		
		if (!f.exists())
			f.mkdir();

		int sizeLimit = 10 * 1024 * 1024;

		
		MultipartRequest mpr = new MultipartRequest(request, savePath, sizeLimit, "UTF-8", new DefaultFileRenamePolicy());
		
		String id = mpr.getParameter("id");
		String password = mpr.getParameter("password");
		String name = mpr.getParameter("name");
		String email = mpr.getParameter("email");
		
		String fileName = null;
		
		try {
			Enumeration<?> fileNames = mpr.getFileNames();
			if (fileNames.hasMoreElements())
			{
				fileName = mpr.getFilesystemName(fileNames.nextElement()
						.toString());
			}
		}catch (Exception e)
		{
			
		}

		DatabaseConnector conn = new DatabaseConnector();
		PrintWriter respOut = response.getWriter();
		
		ArrayList<UserInfo> ui = conn.getUserInfo(id, true);
		
		if (ui == null || ui.size() == 0)
		{
			String sql = String.format("insert into `usr_info` (`id`, `name`, `password`, `email`) values (\"%s\", \"%s\", \"%s\", \"%s\")", id, name, password, email);
			int result = conn.query(sql);
			
			if (result > 0)
			{	
				if (fileName == null) {
					Log.d(id + "'s profile image is not found.");
				} else {
					sql = String.format("update `usr_info` set `image`=\"%s\" where `id`=\"%s\"", fileName, id);
					
					conn.query(sql);
				}
				
				sql = String.format("insert into `login_info` (`id`) values (\"%s\")", id);
				conn.query(sql);
				
				Log.d(id + " is registered.");
				UserInfo userInfo = conn.getUserInfo(id, true).get(0);
				JSONObject obj = new JSONObject();
				obj.put("status", "ok");
				obj.put("id", id);
				obj.put("name", userInfo.getName());
				obj.put("email", userInfo.getEmail());
				if (fileName != null)
				{
					obj.put("image", fileName);
				}
				respOut.println(obj.toJSONString());
			}
			else respOut.println("{ \"status\": \"fail\" }");
		}
		else
		{
			Log.d("Register fail: " + id + " is already registered.");
			respOut.println("{ \"status\": \"duplicate\" }");
		}		
	}

}
